//-----------导航栏时钟开始------------
function check(val) {
    if (val < 10) {
        return ("0" + val);
    } else {
        return (val);
    }
}

function getTime() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minutes = date.getMinutes();
    var second = date.getSeconds();
    var timestr = year + "年" + month + "月" + day + "日 " + check(hour) +
        "时" + check(minutes) + "分" + check(second) + "秒";
    $("#headBarTime").text(timestr);
}

function getTimes() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minutes = date.getMinutes();
    var second = date.getSeconds();
    var timestr = year + "-" + month + "-" + day + " " + check(hour) +
        ":" + check(minutes) + ":" + check(second);
    return timestr;
}
//-----------导航栏时钟结束------------
//-----------密度计算开始------------弃用此函数
// function caculate_density(){
//   var northArea;
//   var southArea;    

//   if (window.XMLHttpRequest){
//     xmlhttp=new XMLHttpRequest();
//   }else{
//     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
//   }
//   xmlhttp.onreadystatechange=function(){
//     if (xmlhttp.readyState==4 && xmlhttp.status==200){
//       document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
//     }
//   }
//   xmlhttp.open("GET","JavaScript/ajax/caculate_density.php",true);
//   xmlhttp.send();
// }
//-----------密度计算结束------------
//-----------通知显示开始------------
function displayNotice() {

    // if (window.XMLHttpRequest){
    //   xmlhttp=new XMLHttpRequest();
    // }else{
    //   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    // }
    // xmlhttp.onreadystatechange=function(){
    //   if (xmlhttp.readyState==4 && xmlhttp.status==200){
    //     document.getElementById("mainAreaMessageBar").innerHTML=xmlhttp.responseText;
    //   }
    // }
    // xmlhttp.open("GET","JavaScript/ajax/getNotice.php",true);
    // xmlhttp.send();
    $.get("JavaScript/ajax/getNotice.php", {}, function(data) {
        $("#mainAreaMessageBar").html(data);
    });
}
//-----------通知显示结束------------
//-----------地图加载开始------------
function initMap() {
    //定义map变量，调用 TMap.Map() 构造函数创建地图
    map = new TMap.Map(document.getElementById('mainAreaMapArea'), {
        center: new TMap.LatLng(39.957233, 116.804253), //设置地图中心点坐标
        zoom: 17, //设置地图缩放级别
        minZoom: 17, //此处设置地图的缩放级别  最小值是6
        maxZoom: 21,
        pitch: 0, //设置俯仰角
        rotation: 90, //设置地图旋转角度
        mapStyleId: 'style 1 black'
    });
    var imageSW = new TMap.LatLng(39.952555, 116.801207);
    var imageNE = new TMap.LatLng(39.961792, 116.807426);
    var imageLatLngBounds = new TMap.LatLngBounds(imageSW, imageNE);
    var imageGroundLayer = new TMap.ImageGroundLayer({
        bounds: imageLatLngBounds,
        src: "./img/mapBorder.png",
        map: map
    });
    //创建容器
    markerLayer = new TMap.MultiMarker({
        map: map, //指定地图容器
        //样式定义
        styles: {
            //创建一个styleId为"myStyle"的样式（styles的子属性名即为styleId）
            "myStyle": new TMap.MarkerStyle({
                "width": 20, // 点标记样式宽度（像素）
                "height": 20, // 点标记样式高度（像素）
                "src": './img/user.svg', //图片路径
                //焦点在图片中的像素位置，一般大头针类似形式的图片以针尖位置做为焦点，圆形点以圆心位置为焦点
                "anchor": { x: 16, y: 32 }
            }),
            "OutStyle": new TMap.MarkerStyle({
                "width": 35, // 点标记样式宽度（像素）
                "height": 35, // 点标记样式高度（像素）
                "src": './img/outstyle.png', //图片路径
                //焦点在图片中的像素位置，一般大头针类似形式的图片以针尖位置做为焦点，圆形点以圆心位置为焦点
                "anchor": { x: 18, y: 18 }
            }),
            "FirStyle": new TMap.MarkerStyle({
                "width": 50, // 点标记样式宽度（像素）
                "height": 50, // 点标记样式高度（像素）
                "src": './img/alertPosition.png', //图片路径
                //焦点在图片中的像素位置，一般大头针类似形式的图片以针尖位置做为焦点，圆形点以圆心位置为焦点
                "anchor": { x: 18, y: 18 }
            })
        },
        //点标记数据数组
        geometries: [{
            "id": 1000, //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
            "styleId": "myStyle", //指定样式id
            "position": new TMap.LatLng(0, 0), //点标记坐标位置
            "properties": { //自定义属性
                "title": "userid"
            }
        }]
    });

    //创建点击事件绑定
    var infoWindow = new TMap.InfoWindow({
        map: map,
        position: new TMap.LatLng(39.957233, 116.804253),
        offset: { x: 0, y: -32 } //设置信息窗相对position偏移像素

    });
    infoWindow.close(); //初始关闭信息窗关闭
    //监听标注点击事件
    markerLayer.on("click", function(evt1) {
        //设置infoWindow
        infoWindow.open(); //打开信息窗
        infoWindow.setPosition(evt1.geometry.position); //设置信息窗位置
        infoWindow.setContent(evt1.geometry.properties['title'].toString()); //设置信息窗内容
    });
    //绑定点击事件
    map.on("click", function(evt2) {
        $("#showPosition").text(evt2.latLng.getLat().toFixed(6) + "," + evt2.latLng.getLng().toFixed(6));
    })
}
//-----------地图加载结束------------
//-----------提交表单不跳转开始------------
function saveReport() {
    // jquery 表单提交 
    $("#showDataForm").ajaxSubmit(function(message) {
        // 对于表单提交成功后处理，message为提交页面saveReport.htm的返回内容 
    });
    return false; // 必须返回false，否则表单会自己再做一次提交操作，并且页面跳转 
}
//-----------提交表单不跳转结束------------
//-------------提交登录开始--------
function post_login() {
    var u = $("#username").val(); //取输入的用户名
    var p = $("#pwd").val(); //取输入的密码
    var c = document.getElementById("remember");
    //      var b_p=base64encode(p);
    checks = false;
    var oRemember = $(".remember");
    if (u == "" || p == "") {

        $(".tips").html("<b>账号或者密码不能为空！</b>");
        $(".tips b").css("color", "red");
        return false;
    }

    if (c.checked) {
        checks = true;
    } else {
        checks = false;
    }
    //调ajax
    $.ajax({
        url: "php/login.php",
        data: { username: u, pwd: p }, //第二个u和p只是变量，可以随意写，dengluchuli.php里面的u和p都是第一个。
        type: "POST",
        dataType: "json",
        success: function(data) {
            if (data.code == "OK") //要加上去空格，防止内容里面有空格引起错误。
            {
                $(".tips").html("<b>登录成功,转跳中...</b>");
                //                      $("#headBarAccount").html("<b>当前账号："+data.username+"|"+"管理员"+"</b>"+"&nbsp"+"<a id='outlogin' href="+""+" ="+"deleCookie('username')"+">退出登录</a>");
                $(".tips b").css("color", "yellow");
                setCookie("username", data.username, 7);
                if (checks) {
                    setCookie("reusername", data.username, 14);
                    setCookie("check", "true", 14);
                    setCookie("pwd", p, 14);

                }
                setTimeout(function() {
                    window.location.reload();
                }, 2000);
            } else {
                $(".tips").html("<b>账号或者密码错误！</b>");
                $(".tips b").css("color", "red");
            }

        }

    });
}
// -------------登录开始------------
function login() {
    var btn = document.querySelector(".btn"); //获取元素
    var mask = document.querySelector(".mask");
    var login = document.querySelector(".login");
    btn.onclick = function() { //绑定点击事件
        var event = event || window.event; //兼容问题
        stopBuble(event); //调用阻止事件冒泡函数
        mask.style.display = "block"; //JS动态让元素显示
        login.style.display = "block";
        document.onclick = function() {
            var event = event || window.event;
            var target = event.target || event.srcElement; //事件委托兼容写法
            if (target.className == "btm-exit") { //事件委托
                mask.style.display = "none";
                login.style.display = "none";
            } else {}
        }
    }

    function stopBuble(e) { //阻止事件冒泡函数
        if (e.stopPropagation) {
            e.stopPropagation();
        } else {
            e.cancelBubble = true;
        }
    }
}
// -------------登录结束------------
// -------------登录s开始------------
function logins() {
    var btn = document.querySelector(".btn"); //获取元素
    var mask = document.querySelector(".mask");
    var login = document.querySelector(".login");
    var event = event || window.event; //兼容问题
    stopBuble(event); //调用阻止事件冒泡函数
    mask.style.display = "block"; //JS动态让元素显示
    login.style.display = "block";
    document.onclick = function() {
        var event = event || window.event;
        var target = event.target || event.srcElement; //事件委托兼容写法
        if (target.className == "btm-exit") { //事件委托
            mask.style.display = "none";
            login.style.display = "none";
        } else {}
    }

    function stopBuble(e) { //阻止事件冒泡函数
        if (e.stopPropagation) {
            e.stopPropagation();
        } else {
            e.cancelBubble = true;
        }
    }
}
// -------------登录s结束------------

// -------------区域人数统计开始-----
function caculateDensity() {
    $.get("JavaScript/ajax/caculateDensity.php", {}, {});
}

// -------------区域人数统计结束-----

// -------------状态框开始----------
function stateBar() {
    $.get("JavaScript/ajax/stateBar.php", {}, function(data) {
        $("#mainAreaStatusBar").html(data);
    });
}
// -------------状态框结束----------
// -------------状态框信息回调开始---------
//function stateBarRequest(){
//	$totalNum = parseInt($("mainAreaStatusBarAreaNorthNum").text())+parseInt($("mainAreaStatusBarAreaSouthNum").text());
//	$.post("JavaScript/ajax/stateBarRequest.php",{
//		totalNum : $totalNum,
//		northNum : parseInt($("mainAreaStatusBarAreaNorthNum").text()),
//		southNum : parseInt($("mainAreaStatusBarAreaSouthNum").text()),
//	});
//}
// -------------状态框信息回调结束---------
// -------------设备提示开始---------
function deviceAlret() {
    if (window.innerWidth < window.innerHeight) {
        alert("此页面在竖屏设备上可能显示不佳，建议横屏使用或使用微信小程序。");
    }
}
// -------------设备提示结束---------

// //-----------设置cookie开始------------
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/";
}


//-----------设置cookie结束------------

// //-----------删除cookie开始------------
function deleCookie(cname) {
    var d = new Date();
    d.setTime(d.getTime() - (1 * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=; " + expires + "; path=/";
    $.ajax({
        url: "./php/loginout.php",
        data: {},
        type: "POST",
        dataType: "json",
        success: function(data) {
            if (data.code == 1) {} else {
                alert('功能异常');
            }
        }
    });
}

//-----------删除cookie结束------------

// //-----------检测cookie开始------------
function checkCookie() {

    var username = getCookie("username");
    var reusername = getCookie("reusername");
    var pwd = getCookie("pwd");
    var checks = getCookie("check");
    var c = document.getElementById("remember");
    c.checked = checks;
    if (username != "") {
        $(".btn").css("display", "none");
        $.ajax({
            url: "./php/checkcoookie.php",
            data: {}, //第二个u和p只是变量，可以随意写，dengluchuli.php里面的u和p都是第一个。
            type: "POST",
            dataType: "json",
        });
        $("#headBarAccount").html("<b>当前账号：" + username + "|" + "管理员" + "</b>" + "&nbsp" + "<a id='outlogin' href=" + "index.html" + " onclick=" + "deleCookie('username')" + ">退出登录</a>");
        setTimeout(function() { getpostion('out');
            getpostion('fir') }, 500);
    } else if (checks) {
        $("#username").val(reusername);
        $("#pwd").val(pwd);
    } else {
        $(".btn").css("display", "");
        alert("请先登录系统！");
        logins();
    }
}
//-----------检测cookie结束------------


// //-----------获取cookie开始------------
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}
//-----------检测cookie结束------------
//-----------检测复选框 记住密码- 开始-------
function rem() {
    var c = document.getElementById("remember");
    if (!c.checked) {
        setCookie("check", "false", 7);
        deleCookie("pwd");
        deleCookie("reusername");
        deleCookie("check");
    }
}
//-----------检测复选框 记住密码- 结束-------

//-----------获取用户位置信息开始-------
function checkmins(minus, num) {
    var a;
    var b;
    b = minus - num;
    if (b <= 9 && b >= 0) {
        a = "0" + b;
        return a;
    } else if (b > 9) {
        return b;
    }

}

var tf = 'true'; //全局属性 让他只调用一次
var stuNum = 0;

function getpostion(type) {
    var times = new Date();

    $.ajax({
        url: "./php/getuserposition.php",
        data: { TYPE: type }, //第二个u和p只是变量，可以随意写，dengluchuli.php里面的u和p都是第一个。
        type: "POST",
        dataType: "json",
        success: function(data) {
            value = data;
            if (data.type == "user") {
                document.getElementById("stopuserPlace").disabled = "";
                document.getElementById("getuserPlace").disabled = "disabled";
                document.getElementById("getuserPlace").style = "background-color: #000;"
                document.getElementById("stopuserPlace").style = "background-color: #1E90FF;"
                flushUserPlace(5000, tf);
                if (data.num > 0) //要加上去空格，防止内容里面有空格引起错误。  onclick="+"deleCookie('username')"+
                {
                    stuNum = data.num;

                    for (var i = 0; i < data.num; i++) {
                        var html = '该名学生当前位置[lat:' + data.info[i]['userlat'] + 'log:' + data.info[i]['userlog'] + ']<br>位置最后更新时间[' + data.info[i]['addtime'] + ']<br>' +
                            '<button class="btn" id="' + data.info[i]['useropenid'] + ' " ' + "onclick=" + 'sendmsgonly("' + data.info[i]['useropenid'] + '")' + '>单独发送通知</button>';
                        addmarker(data.info[i]['useropenid'], html, data.info[i]['userlat'], data.info[i]['userlog'], 'myStyle');
                    }
                } else if (data.num == 0) {
                    alert("数据异常或当前区域无逗留人员！");
                }
            } else if (data.type == "out") {
                if (data.num > 0) //要加上去空格，防止内容里面有空格引起错误。
                {
                    for (var i = 0; i < data.num; i++) {
                        // addmarker(999-i,'<button class="btn" onclick="">登录</button>',data.info[i]['lat'],data.info[i]['log'],'OutStyle');
                        addmarker(999 - i, "[" + data.info[i]['door'] + "]-Max:" + data.info[i]['maxTraffic'], data.info[i]['lat'], data.info[i]['log'], 'OutStyle');
                        // alert(data.info[i]['lat']);
                    }
                } else if (data.num == 0) {
                    alert("出口数据异常，请检查数据库！");
                }
            } else if (data.type == 'fir') {
                if (data.num > 0) {
                    for (var i = 0; i < data.num; i++) {
                        var lat = data.info[i]['emcplace'].split(',');
                        console.log("fir输出", lat);
                        addmarker(900 - i, "[" + data.info[i]['emcName'] + "]-发生时间:" + data.info[i]['time'], lat[0], lat[1], 'FirStyle');
                    }
                }
            }
        }
    });

}
//-----------获取用户位置信息结束-------

//-----------获取用户位置信息开始-------
function stopFlush() {
    console.log("清除任务", "----", flushID);
    clearInterval(flushID)
    document.getElementById("stopuserPlace").disabled = "disabled";
    document.getElementById("getuserPlace").disabled = "";
    document.getElementById("stopuserPlace").style = "background-color: #000;"
    document.getElementById("getuserPlace").style = "background-color: #1E90FF;"
    alert("停止成功！");
}
//-----------实时刷新用户位置结束-------

//-----------实时刷新用户位置开始-------
var id = new Array();
var flushID = 0;

function flushUserPlace(time, change) { //num用户数量,time刷新间隔 单位毫秒
    if (change == 'true') {
        if (id.length > 0) {
            for (var i = 0; i < id.length; i++) {
                console.log(i, "----", id[i]);
                clearInterval(id[i]);
            }
            id = new Array();
            startFlush = setInterval(function() {
                updatema()
            }, time);
            console.log('true增加', startFlush);
            id.push(startFlush);
            flushID = startFlush;
        } else {
            startFlush = setInterval(function() {
                updatema()
            }, time);
            console.log('flase增加', startFlush);
            id.push(startFlush);
            flushID = startFlush;
        }

    }

}
//更新点
function updatema() {
    // markerLayer.setGeometries([]);
    $.ajax({
        url: "./php/getuserposition.php",
        data: { TYPE: 'user' }, //第二个u和p只是变量，可以随意写，dengluchuli.php里面的u和p都是第一个。
        type: "POST",
        dataType: "json",
        success: function(data) {
            if (data.type == "user") {
                if (data.num > 0) //要加上去空格，防止内容里面有空格引起错误。  onclick="+"deleCookie('username')"+
                {
                    stuNum = data.num;
                    for (var i = 0; i < data.num; i++) {
                        markerLayer.remove(data.info[i]['useropenid'])
                        var html = '该名学生当前位置[lat:' + data.info[i]['userlat'] + 'log:' + data.info[i]['userlog'] + ']<br>位置最后更新时间[' + data.info[i]['addtime'] + ']<br>' +
                            '<button class="btn" id="' + data.info[i]['useropenid'] + ' " ' + "onclick=" + 'sendmsgonly("' + data.info[i]['useropenid'] + '")' + '>单独发送通知</button>';
                        updatemarker(data.info[i]['useropenid'], html, data.info[i]['userlat'], data.info[i]['userlog'], 'myStyle');
                    }
                } else if (data.num == 0) {
                    console.log("数据异常或当前区域无逗留人员！");
                }
            }
        },
    });
}
//------------增加点标记开始------------
function addmarker(ids, userid, log, lat, styid) {
    markerLayer.add([{
        "id": ids, //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
        "styleId": styid, //指定样式id
        "position": new TMap.LatLng(log, lat), //点标记坐标位置
        "properties": { //自定义属性
            "title": userid
        }
    }]);
}

function updatemarker(ids, userid, log, lat, styid) {
    markerLayer.updateGeometries([{
        "styleId": styid,
        "id": ids,
        "position": new TMap.LatLng(log, lat),
        "properties": { //自定义属性
            "title": userid
        }
    }])
}

//------------增加点标记结束------------
//添加新通知功能
function addnotices() {
    var name = $("#classname").val(); //取输入的用户名
    var value = $("#notice_value").val(); //取输入的内容
    if (name == "" || value == "") {
        alert("请输入部门或者内容！");
        return;
    }
    var mask = document.querySelector(".mask1");
    var addnotice = document.querySelector(".addnotice");
    $.ajax({
        url: "./php/AddNotice.php",
        data: { user: name, value: value }, //第二个u和p只是变量，可以随意写，dengluchuli.php里面的u和p都是第一个。
        type: "POST",
        dataType: "json",
        success: function(data) {
            if (data.code == 1) {

                alert(data.msg);
                mask.style.display = "none";
                addnotice.style.display = "none";
                $("#classname").value = "";
                $("#notice_value").value = "";
            } else {
                alert(data.msg + "," + "错误代码:" + data.code);
            }
        }
    });
}
//-----------结束
//弹出输入框
function addnotice() {
    var mask = document.querySelector(".mask1");
    var addnotice = document.querySelector(".addnotice");
    $.ajax({
        url: "./php/checktoken.php",
        data: {},
        type: "POST",
        dataType: "json",
        success: function(data) {
            if (data.code == 1) {
                var event = event || window.event; //兼容问题
                stopBuble(event); //调用阻止事件冒泡函数
                mask.style.display = "block"; //JS动态让元素显示
                addnotice.style.display = "block";
                document.onclick = function() {
                    var event = event || window.event;
                    var target = event.target || event.srcElement; //事件委托兼容写法
                    if (target.className == "btm-exit") { //事件委托
                        mask.style.display = "none";
                        addnotice.style.display = "none";
                    }
                }
            } else {
                alert('抱歉，您无此操作权限！');
            }
        }
    });

    function stopBuble(e) { //阻止事件冒泡函数
        if (e.stopPropagation) {
            e.stopPropagation();
        } else {
            e.cancelBubble = true;
        }
    }
}
//-----------结束
//------------手痛添加警情开始--------------
function addEmergency() {
    $.ajax({
        url: "./php/checktoken.php",
        data: {},
        type: "POST",
        dataType: "json",
        success: function(data) {
            if (data.code == 1) {
                $("#clickPosition").css("visibility", "visible");
                $("#addAlertSelect").css("visibility", "visible");
            } else {
                alert('抱歉，您无此操作权限！');
            }
        }
    });

}

function addEmergencyCancle() {
    $("#clickPosition").css("visibility", "hidden");
    $("#addAlertSelect").css("visibility", "hidden");
}

function addEmergencySubmit() {
    var alertPosition = $("#showPosition").text();
    var emcName = window.prompt("请输入警情点特征地标名:")
    var alertmsg = ("此操作将触发园区疏散预案\n确认提交吗？\n提交位置:" + alertPosition);
    var theResponse = window.prompt(alertmsg, "输入y,以确认发布!");
    if (theResponse == "y") {
        $.ajax({
            url: "JavaScript/ajax/startEmergencyResponsePlan.php",
            data: { emcplace: alertPosition, emcName: emcName },
            type: "POST",
            dataType: "json",
        });
        addmarker("fir_coin", 1, alertPosition.split(",")[0], alertPosition.split(",")[1], 'FirStyle');
        addEmergencyCancle();
        var name = $("#classname").val(); //取输入的用户名
        var value = $("#notice_value").val(); //取输入的密码
        var mask = document.querySelector(".mask1");
        var addnotice = document.querySelector(".addnotice");
        $.ajax({
            url: "./php/AddNotice.php",
            data: { user: "指挥中心", value: alertPosition + "出现警情，已执行应急预案！" },
            type: "POST",
            dataType: "json",
            // success: function(data){
            // if(data.code==1){
            // 	alert(data.msg);
            // 	mask.style.display = "none";
            // 	 addnotice.style.display = "none";
            // 	 $("#classname").value="";
            // 	 $("#notice_value").value="";
            // }else{
            // 	alert(data.msg+","+"错误代码:"+data.code);
            // }
            // }
        });
    } else {
        alert("已取消");
        addEmergencyCancle();
    }
}
//------------更改区域状态开始--------------
function changeAreaState() {
    $.ajax({
        url: "./php/checktoken.php",
        data: {},
        type: "POST",
        dataType: "json",
        success: function(data) {
            if (data.code == 1) {
                $("#changeAreaStateSelect").css("visibility", "visible");
            } else {
                alert('抱歉，您无此操作权限！');
            }
        }
    });
}

function changeAreaStateSubmit() {
    var changeState = $("#changeAreaStateSelection").val();
    if (changeAreaState != "疏散中") {
        markerLayer.remove("fir_coin");
    }
    $.ajax({
        url: "JavaScript/ajax/changeState.php",
        data: { value: changeState },
        type: "POST",
        dataType: "json",
        success: function(data) {
            if (data.code == 1) {
                alert(data.msg);

            } else {
                alert(data.msg + "," + "错误代码:" + data.code);
            }
        }
    });
    var username = getCookie("username");
    $.ajax({
        url: "./php/AddNotice.php",
        data: { user: username, value: "状态已修改为:" + changeState },
        type: "POST",
        dataType: "json",
    });

}

function changeAreaStateClose() {
    $("#changeAreaStateSelect").css("visibility", "hidden");
}



//全局推送函数开始--------------------------------------------
//全局推送函数开始--------------------------------------------
function sendMsg() {
    var fir = document.querySelector(".fir");
    var Firnotice = document.querySelector(".Firnotice");
    $.ajax({
        url: "./php/checktoken.php",
        data: {},
        type: "POST",
        dataType: "json",
        success: function(data) {
            if (data.code == 1) {
                var event = event || window.event; //兼容问题
                stopBuble(event); //调用阻止事件冒泡函数
                fir.style.display = "block"; //JS动态让元素显示
                Firnotice.style.display = "block";
                document.onclick = function() {
                    var event = event || window.event;
                    var target = event.target || event.srcElement; //事件委托兼容写法
                    if (target.className == "btm-firexit") { //事件委托
                        fir.style.display = "none";
                        Firnotice.style.display = "none";
                    } else if (target.className == "btm-firreturn") {
                        var send_fir = document.getElementById("send_fir");
                        var check_fir = document.getElementById("check_fir");
                        var input_firnotice = document.getElementById("input_firnotice");
                        input_firnotice.style.left = '20%';
                        send_fir.style.display = 'inline';
                        check_fir.style.display = 'none';

                    } else if (target.className == "btm-fircheck") {
                        var send_fir = document.getElementById("send_fir");
                        var check_fir = document.getElementById("check_fir");
                        var input_firnotice = document.getElementById("input_firnotice");
                        input_firnotice.style.left = '0';
                        send_fir.style.display = 'none';
                        check_fir.style.display = 'inline';
                    }
                }
            } else {
                alert('抱歉，您无此操作权限！');
            }
        }
    });

    function stopBuble(e) { //阻止事件冒泡函数
        if (e.stopPropagation) {
            e.stopPropagation();
        } else {
            e.cancelBubble = true;
        }
    }
}

//全局推送函数开始--------调用发送接口------------------------------------
//全局推送函数开始---------调用发送接口-----------------------------------
　
var all = 0;

function addfirnotices() {
    var title = $("#fir_title").val();
    var times = $("#fir_time").val();
    var time = format(times, 'yyyy-MM-dd HH:mm:ss');
    var place = $("#fir_place").val();
    var tips = $("#fir_tips").val();
    if (title == "") {
        alert("标题不能为空！");
        return;
    } else if (times == "") {
        alert("时间不能为空！");
        return;
    } else if (place == "") {
        alert("地点不能为空！");
        return;
    }
    var msg = "您确定发布小程序通知？操作不可撤销！";
    if (confirm(msg) == true) {

        var log = $(".log");
        var template_id = $('input[name="radioLove"]:checked').val();
        var successnum = 0; //发送成功数量
        var allpeople = 1; //总人数
        var falsenum = 0;
        var turn = 1; //token状态
        var i = 0;
        var useropenid = new Array();
        var true_num = $("#true_num");
        var false_num = $("#false_num");
        var all_num = $("#all_num");
        // var html=new Array();
        // alert(template_id);

        $.ajax({
            url: "./php/useropenid.php",
            data: {},
            type: "POST",
            dataType: "json",
            success: function(data) {
                if (data.num != 0) {
                    // console.log(true_num.innerHTML);
                    allpeople = data.num;
                    all = allpeople;
                    $("#all_num").html("总计[" + allpeople + "]");
                    for (i; i < data.num; i++) {
                        useropenid[i] = data.info[i]['useropenid'];
                        // console.log(true_num.innerHTML);
                        $.ajax({
                            // async:false,
                            url: "./php/sendmesg.php",
                            data: { touser: useropenid[i], template_id: template_id, title: title, time: time, place: place, tips: tips },
                            type: "POST",
                            dataType: "json",
                            success: function(date) {

                                if (date.code == 1) {
                                    turn = 1;
                                    if (date.data['errmsg'] == 'ok') {
                                        successnum = successnum + 1;
                                        $("#true_num").html("成功[" + successnum + "]");
                                        // html='<li>'+getTimes()+":["+useropenid[i]+'] 发送成功</li>';
                                        // console.log(useropenid);
                                    } else {
                                        // html='<li>'+getTimes()+":["+useropenid[i]+'] 错误代码：'+date.data['errcode']+'</li>';
                                        // console.log(useropenid);
                                        falsenum = falsenum + 1;
                                        $("#false_num").html("失败[" + falsenum + "]");
                                    }
                                } else {
                                    // alert('token已失效,重新获取成功！请重新操作！');
                                    turn = 0;
                                    // html='<li>'+getTimes()+':发送密钥token失效，重新获取完成,重新操作!</li>';
                                    // $(".log").append("<li>"+getTimes()+":["+useropenid+"] 发送失败,错误代码:"+date.data['errcode']+"</li>");
                                }

                            }

                        });

                        if (turn == 0) {
                            i = 999;
                            // alert('token已失效,重新获取成功！请重新操作！');
                        }

                        // $(".log").append(html);
                        // alert("<li>"+getTimes()+": token已失效，发送失败！请重新操作！</li>");

                    }


                } else {
                    alert('读取小程序用户openid失败！');
                }
            }
        });

    } else {
        return false;
    }

}
//全局推送函数开始--------时间转换------------------------------------
//全局推送函数开始---------时间转换-----------------------------------
function format(time, format) {
    var t = new Date(time);
    var tf = function(i) { return (i < 10 ? '0' : '') + i };
    return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a) {
        switch (a) {
            case 'yyyy':
                return tf(t.getFullYear());
                break;
            case 'MM':
                return tf(t.getMonth() + 1);
                break;
            case 'mm':
                return tf(t.getMinutes());
                break;
            case 'dd':
                return tf(t.getDate());
                break;
            case 'HH':
                return tf(t.getHours());
                break;
            case 'ss':
                return tf(t.getSeconds());
                break;
        }
    })
}
//单独发送微信通知
function sendmsgonly(useropenid) {
    $.ajax({
        url: "./php/checktoken.php",
        data: {},
        type: "POST",
        dataType: "json",
        success: function(data) {
            if (data.code == 1) {

                var title = prompt("请输入标题", "");
                if (title == null)
                    return false;
                var place = prompt("请输入地点", "");
                if (title == null)
                    return false;
                var tips = prompt("请输入备注", "");
                if (title == null)
                    return false;
                var time = getTimes();
                var template_id = "-tVTci9trWVp8EL9kTOjCsW-Eqz6HJAzJxr33fIdzyg";
                var r = confirm("确认您输入的信息:\n    " +
                    "\n标题:" + title +
                    "\n地点:" + place +
                    "\n时间:" + time +
                    "\n备注:" + tips +
                    "\n用户openid:" + useropenid
                );
                if (r == true) {
                    $.ajax({
                        url: "./php/sendmesg.php",
                        data: { touser: useropenid, template_id: template_id, title: title, time: time, place: place, tips: tips },
                        type: "POST",
                        dataType: "json",
                        success: function(date) {

                            if (date.code == 1) {

                                if (date.data['errmsg'] == 'ok') {
                                    document.getElementById(useropenid).innerText = "发送成功";
                                }
                            } else {
                                // alert('token已失效,重新获取成功！请重新操作！');
                                document.getElementById(useropenid).innerText = "发送失败";

                            }

                        }
                    });
                } else {
                    return false;
                }



            } else {
                alert('抱歉，您无此操作权限！');
            }
        }
    });

}

//获取发送日志消息开始
function getlog() {
    var number = document.getElementById("numbers").value;
    $.get("php/getlog.php?num=" + number, {}, function(data) {
        $('.log').append(data);
    });
}

function remove() {
    $("tr").remove(".italic"); //清空查询的结果
}

// 主函数，页面加载时调用，其他函数写在主函数上边！！！
// //-----------载入功能开始------------
function start() {
    deviceAlret();
    getTime();
    displayNotice();
    // caculateDensity();
    stateBar();
    window.setInterval("getTime()", 1000);
    window.setInterval("displayNotice()", 5001);
    window.setInterval("stateBar()", 10003);
    // window.setInterval("caculateDensity()",10002);;
    login();
    initMap(); //创建和初始化地图
    checkCookie();

}
//-----------载入功能结束------------
// 主函数，页面加载时调用，其他函数写在主函数上边！！！